package com.hgnu.dorm.service.impl;


import com.hgnu.dorm.domain.dto.UserPageQueryDto;
import com.hgnu.dorm.domain.po.PageBean;
import com.hgnu.dorm.domain.po.User;
import com.hgnu.dorm.exception.BaseException;
import com.hgnu.dorm.mapper.UserMapper;
import com.hgnu.dorm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(User user) {
        return userMapper.login(user);
    }

    @Override
    public void register(User user) {
        User u = userMapper.findByAccount(user.getAccount());
        if(u != null){
            throw  new BaseException("该账户已存在");
        }
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setRoleId(1);
        user.setStatus(1);
        userMapper.insertUser(user);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.getById(id);
    }

    @Override
    public void updateStatus(Integer id) {
        User user = userMapper.getById(id);
        if(user == null){
            throw new BaseException("该用户不存在");
        }
        Integer roleId = user.getRoleId();
        if(roleId == null){
            throw new BaseException("出错了");
        }
        if(roleId == 0){
            throw new BaseException("无法禁用管理员账户");
        }
        user.setStatus(user.getStatus()==1?0:1);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateUser(user);
    }

    @Override
    public int delete(Long[] ids) {
        Integer count = userMapper.countStatus(ids);
        if(count>0){
            throw new BaseException("无法删除正在使用或为管理员的账户");
        }
        return userMapper.deleteUserByIds(ids);
    }

    @Override
    public void insertUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        if(user.getStatus()==null){
            user.setStatus(1);
        }
        if(user.getRoleId()==null){
            user.setRoleId(1);
        }
        if(user.getPassword()==null || user.getPassword()==""){
            user.setPassword("123456");
        }
        userMapper.insertUser(user);
    }

    @Override
    public void updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateUser(user);
    }

    @Override
    public PageBean page(UserPageQueryDto dto) {
        Long total = userMapper.count(dto);
        if(dto.getPage()<=0){
            dto.setPage(1);
        }
        if(dto.getPageSize()<=0){
            dto.setPageSize(10);
        }
        Integer start = (dto.getPage() - 1) * dto.getPageSize();
        dto.setStart(start);
        List<User> page = userMapper.page(dto);
        return new PageBean(total, page);
    }
}
